from .models import Response, Selectors
from ..utils import match_domain
import json
from pathlib import Path


class Router:
    config: dict

    def __init__(self, router_config_file=None):
        if not router_config_file:
            router_config_file = (
                Path(__file__).parent / Path("../data/selectors.json")
            ).resolve()
        with open(router_config_file, encoding="utf-8") as f:
            self.config = json.load(f)
        assert self.validate_config()

    def dispatch(self, response: Response) -> Selectors:
        host = response.url.host
        for pat in self.config:
            if match_domain(host, pat):
                return Selectors(**self.config.get(pat))
        else:
            return None

    def validate_config(self):
        """校验配置文件是否合法"""
        return True
